/**
 * 数据库配置服务
 * 作者：GodMainCode
 * 创建时间：2024-01-17
 * 修改时间：2024-01-17
 * 修改人：GodMainCode
 */

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { User } from '../modules/user/entities/user.entity';
import { Role } from '../modules/role/entities/role.entity';
import { Permission } from '../modules/permission/entities/permission.entity';

@Injectable()
export class DatabaseConfig {
  constructor(private configService: ConfigService) {}

  /**
   * 获取数据库配置
   * @returns TypeOrmModuleOptions
   */
  getTypeOrmConfig(): TypeOrmModuleOptions {
    const dbType = this.configService.get<string>('DB_TYPE');

    const baseConfig = {
      entities: [User, Role, Permission],
      synchronize: this.configService.get<boolean>('DB_SYNC'),
      logging: this.configService.get<string>('NODE_ENV') === 'development',
      autoLoadEntities: true,
    };

    if (dbType === 'postgres') {
      return {
        type: 'postgres',
        host: this.configService.get<string>('POSTGRES_HOST'),
        port: this.configService.get<number>('POSTGRES_PORT'),
        username: this.configService.get<string>('POSTGRES_USERNAME'),
        password: this.configService.get<string>('POSTGRES_PASSWORD'),
        database: this.configService.get<string>('POSTGRES_DATABASE'),
        ...baseConfig,
      };
    }

    // 默认使用 MySQL
    return {
      type: 'mysql',
      host: this.configService.get<string>('MYSQL_HOST'),
      port: this.configService.get<number>('MYSQL_PORT'),
      username: this.configService.get<string>('MYSQL_USERNAME'),
      password: this.configService.get<string>('MYSQL_PASSWORD'),
      database: this.configService.get<string>('MYSQL_DATABASE'),
      ...baseConfig,
    };
  }
} 